package ori.iori.lxListener;

import java.text.NumberFormat;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.ProgressListener;

public class UploadListener implements ProgressListener {

	private double megaBytes = -1;
	private HttpSession session;
	public UploadListener(HttpServletRequest request) {
		session = request.getSession();
	}
	public void update(long pBytesRead, long pContentLength, int pItems) {
		Object obj_progress_disabled = session.getAttribute("progress_disabled");
		if (null != obj_progress_disabled) {
			boolean progress_disabled = Boolean.parseBoolean(obj_progress_disabled.toString());
			if (false == progress_disabled) {
				session.removeAttribute("progress_num");
				return;
			}
		}
		double mBytes = (double)pBytesRead / 1000000;
		double total = (double)pContentLength / 1000000;
	       if (megaBytes == mBytes) {
	           return;
	       }
//	       System.out.println("total====>" + total);
//	       System.out.println("mBytes====>" + mBytes);
	       megaBytes = mBytes;
//	       System.out.println("megaBytes====>" + megaBytes);
//	       System.out.println("We are currently reading item " + pItems);
	       if (pContentLength == -1) {
//	           System.out.println("So far, " + pBytesRead + " bytes have been read.");
	       } else {
//	           System.out.println("So far, " + pBytesRead + " of " + pContentLength + " bytes have been read.");
	          double read = (mBytes / total);
	          NumberFormat nf = NumberFormat.getPercentInstance();
	          int progress_num = Integer.parseInt(new java.text.DecimalFormat("0").format(read * 100));
	          System.out.println("read===>" + nf.format(read));//生成读取的百分比 并放入session中
	          System.out.println("progress_num===>" + progress_num);//生成读取的百分比 并放入session中
	          session.setAttribute("progress_num", progress_num);
	       }
	}

}
